//define the variable
var xml_request;
var dataTable;
var dataDiv;
var dataTableBody;
var count = 0;
var countTotal = 0;
var skill;
var skillBranch;
var questionNo;
var duration;
var skill_option;
var skillBranch_option;
var tr;
var XMLHttpReq;
var dropdownListTag;
var message;

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: Pop up modify grade window
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function updateGrade(eventSrc) {
	var trNode = $(getParentTR(eventSrc));
	inputGroupInfo(trNode);
	// var val = showModalDialog("../Pages/Jsp/User/modifyGroupDialog.jsp",
	// groupRes, "dialogWidth:750px;dialogHeight:400px;");
	showDiv();
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: Input grade information to the pop up window
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function inputGroupInfo(trNode) {
	var gradeName = trNode.find("input[id='gradeName']").attr("value");
	var minYear = trNode.find("input[id='minYear']").attr("value");
	var maxYear = trNode.find("input[id='maxYear']").attr("value");
	var desc = trNode.find("input[id='desc']").attr("value");

	$("input[id='hiddenGradeName']").attr("value", gradeName);
	$("input[id='hiddenMinYear']").attr("value", minYear);
	$("input[id='hiddenMaxYear']").attr("value", maxYear);
	$("textarea[id='hiddenGradeDesc']").attr("value", desc);
	
	$("input[id='hiddenGrade']").attr("value", gradeName);
	$("input[id='hideMinYear']").attr("value", minYear);
	$("input[id='hideMaxYear']").attr("value", maxYear);
	$("input[id='hideDescription']").attr("value", desc);
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: Modify grade. Send the request and data to action by AJAX
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function modifyGrade() {
	var showGradeName= $("input[id='hiddenGradeName']").attr("value");
	var showMinYear=$("input[id='hiddenMinYear']").attr("value");
	var showMaxYear = $("input[id='hiddenMaxYear']").attr("value");
	var showDesc = $("textarea[id='hiddenGradeDesc']").attr("value");
//	if(showGradeName == null || showGradeName==""){
//		alert("Please fill in \'Grade\'!");
//		return false;
//	}else if(showMinYear == null || showMinYear=="" || showMaxYear == null || showMaxYear==""){
//		alert("Please fill in years of experience!");
//		return false;
//	}else if(parseInt(showMinYear)>parseInt(showMaxYear)){
//		alert("The year format is not right!");
//		return false;
//	}else if(showDesc == null || showDesc == ""){
//		alert("Please fill in description!");
//		return false;
//	}
	
//	$("#loadingPic").show();
//	$("input").attr('disabled', ' true');
//	$("textarea").attr('disabled', ' true');
	$("#loadingPic").show();
	$("input").attr('disabled',' true');
	$("textarea").attr('disabled',' true');
	$("select").attr('disabled','true');
	$("#errors").empty();

	var groupData = {
		"gradeName" : $("input[id='hiddenGradeName']").attr("value"),
		"hiddenGrade" : $("input[id='hiddenGrade']").attr("value"),
		"minYear" : $("input[id='hiddenMinYear']").attr("value"),
		"maxYear" : $("input[id='hiddenMaxYear']").attr("value"),
		"description" : $("textarea[id='hiddenGradeDesc']").attr("value")
	};

	groupData = JSON2.stringify(groupData);
	var url = "../createGrade/updateGrade.do";

	$.ajax( {
		url : url,
		data : groupData,
		type : "POST",
		processData : true,
		contentType : "application/json",
		timeout : 20000,
		dataType : "json",
		success : function(res) {
			modifyGradeSucc(res);
		},
		error: function(message) { $("#loadmessage").append(message+"<br/>Error!Please refresh this page."); 
		}
	});
	
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: get the parent TR node by where action happened
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function getParentTR(ctlObj) {
	var trNode = ctlObj;
	while (true) {
		if (trNode == null || trNode.tagName.toLowerCase() == "tr") {
			break;
		}
		trNode = trNode.parentNode;
	}
	return trNode;
}

function getParentForm(ctlObj) {
	var trNode = ctlObj;
	while (true) {
		if (trNode == null || trNode.tagName.toLowerCase() == "form") {
			break;
		}
		trNode = trNode.parentNode;
	}
	return trNode;
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: Callback function when modify grade successfully
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function modifyGradeSucc(data) {
	var res = data;
	message = data.notice;
	$("#noticeTxt").show();
	$("#noticeTxt").empty();
	$("#noticeTxt").append(data.notice);
	
	
	/*var res = data;
	$(".succTxt").show();
	$("#noticeTxt").append(data.notice);*/

	// var gradeName = data.grade.gradeName;
	if(data.status == 0)
	{
	var gradeName = data.grade.hiddenGrade;
	var ids = $("input[title='gradeName']");
	$.each(ids, function(i) {
		if (ids[i].value == gradeName) {
			var trNode = $(getParentTR(ids[i]));
			trNode.find("input[id='gradeName']").attr("value",
					data.grade.gradeName);
			trNode.find("input[id='desc']").attr("value", data.grade.desc);
			trNode.find("input[id='minYear']")
					.attr("value", data.grade.minYear);
			trNode.find("input[id='maxYear']")
					.attr("value", data.grade.maxYear);

			trNode.find("span[id='gradeName']").html(data.grade.gradeName);
			trNode.find("span[id='desc']").html(data.grade.desc);
			trNode.find("span[id='minYear']").html(data.grade.minYear);
			trNode.find("span[id='maxYear']").html(data.grade.maxYear);
		}
	});
	
	$("#errors").hide();
	resetGroupControls();
	}else{
		$("#errors").show();
		$("#noticeTxt").hide();
		var errors =  data.errors;
		$.each(errors,function(i){
			$("#errors").append(errors[i].error + "<br/>");
		});
		resetGroupControls();
	}

//	window.setTimeout(function() {
//		resetGradeDialog();
//	}, 5000);
}
function resetGroupControls(){
	$("input").attr('disabled',false);
	$("textarea").attr('disabled',false);
	$("select").attr('disabled',false);
	$("#loadingPic").hide();
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: Reset Group Dialog
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function resetGradeDialog() {
	$("input").attr('disabled', false);
	$("textarea").attr('disabled', false);
	$("#noticeTxt").empty();
	$(".succTxt").hide();
	$("#loadingPic").hide();
	closeDiv();
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality:
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function fun_select(element) {
	var i;
	for (i = 0; i < element.length; i++) {
		if (element.options[i].selected == true) {
			element.title = element.options[i].innerHTML;
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: Reset Group Dialog
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/

function createXMLHttpRequest() {
	if (window.XMLHttpRequest) { // Mozilla Browser
		XMLHttpReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE Browser
		try {
			XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
}
/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: send request function
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/

function sendRequest(url) {
	createXMLHttpRequest();
	XMLHttpReq.open("GET", url, true);
	XMLHttpReq.onreadystatechange = processResponse;// give response function
	XMLHttpReq.send(null); // send request
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality:The function is handle return information
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function processResponse() {
	if (XMLHttpReq.readyState == 4) { // check object status
		if (XMLHttpReq.status == 200) { // handle the information if response
										// successful
			updateMenu();
		} else { // page is exception
			alert("your request has exception");
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: function of updating menu
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/

function updateMenu() {

	var xmlDoc = XMLHttpReq.responseXML.documentElement;
	var xsel = xmlDoc.getElementsByTagName("select");
	var subRoot = document.getElementById(dropdownListTag);
	subRoot.options.length = 0;

	var rangXml = xmlDoc.getElementsByTagName("rang");
	var rang = document.getElementById("rang");
	var rangValue = rangXml[0].firstChild.nodeValue;

	if (rangValue == "select") {
		rang.innerHTML = "";
	} else {
		rang.innerHTML = rangValue;
	}

	for ( var i = 0; i < xsel.length; i++) {

		try {
			var xValue = xsel[i].childNodes[0].firstChild.nodeValue;
			var xText = xsel[i].childNodes[1].firstChild.nodeValue;
			var option = new Option(xText, xValue);
			subRoot[i] = option;
			// subRoot.add(option);
		} catch (e) {
			xValue = "";
			var xText = xsel[i].childNodes[1].firstChild.nodeValue;
			var option = new Option(xText, xValue);
			subRoot[i] = option;
			// subRoot.add(option);
		}
	}
}
/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: function of creating cache menu
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function showSubMenu(url, component, tagType) {
	dropdownListTag = tagType;
	var idValue = component.options[component.selectedIndex].value;
	sendRequest(url + "?idValue=" + idValue);
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: function of creating cache menu
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function option_select_change(url, component,tagType) {
//	var trNode = $(getParentForm(eventSrc));
//	var gradeName = trNode.find("select[id='gradeName']").attr("value");
//	var year = trNode.find("select[id='year']").attr("value");
//	var skillId = trNode.find("select[id='skill']").attr("value");
//
//	sendSkillRequest(url + "?skillId=" + skillId+"&gradeName="+gradeName+"&year="+year);
//	
	var i;
	for (i = 0; i < element.length; i++) {
		if (element.options[i].selected == true) {
			element.title = element.options[i].innerHTML;
		}
	}
	showSubSkillMenu(url, element);
	var sel = document.getElementById("skillBranch");

	sel.Value = "";

}
function showSubSkillMenu(url, component) {
	dropdownListTag = tagType;
	var idValue = component.options[component.selectedIndex].value;
	sendSkillRequest(url + "?idValue=" + idValue);
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: send skill request
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function sendSkillRequest(url) {
	createXMLHttpRequest();
	XMLHttpReq.open("GET", url, true);
	XMLHttpReq.onreadystatechange = processSkillResponse;// give response
															// function
	XMLHttpReq.send(null); // send request
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: process the skill reponse
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function processSkillResponse() {
	if (XMLHttpReq.readyState == 4) { // check object status
		if (XMLHttpReq.status == 200) { // handle the information if response
										// successful
			updateSkillMenu();
		} else { // page is exception
			alert("your request has exception");
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: update skill menu
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function updateSkillMenu() {
	var xmlDoc = XMLHttpReq.responseXML.documentElement;
	var xsel = xmlDoc.getElementsByTagName("select");
	var subRoot = document.getElementById(dropdownListTag);
	subRoot.options.length = 0;
	for ( var i = 0; i < xsel.length; i++) {

		try {
			var xValue = xsel[i].childNodes[0].firstChild.nodeValue;
			var xText = xsel[i].childNodes[1].firstChild.nodeValue;
			var option = new Option(xText, xValue);
			subRoot[i] = option;
			// subRoot.add(option);
		} catch (e) {
			xValue = "";
			var xText = xsel[i].childNodes[1].firstChild.nodeValue;
			var option = new Option(xText, xValue);
			subRoot[i] = option;
			// subRoot.add(option);
		}
	}
	
	document.getElementById("listSKillBranch").style.display="";
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: clear all the data
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function clearData(stateVal) {
	getXMLHttpRequest();
	if (xml_request) {
		xml_request.open("GET", url, true);
		xml_request.onreadystatechange = completeClear;
		xml_request.send(null);
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: clear all the data
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function completeClear() {
	if (xml_request.readyState == 4) {
		if (xml_request.status == 200) {

			var i;
			countTotal = countTotal + 2;
			for (i = 2; i < countTotal; i++) {
				dataTableBody.removeChild(dataTableBody.childNodes[2]);
			}
			countTotal = 0;
			setGenerate();

			// getResult(stateVal);
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: delete one row
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function deleteRow(element, stateVal) {

	tr = document.getElementById("tr" + element.id);

	var url = "../maintainGrade/addMultipleSkills.do?method=" + stateVal + "&id="
			+ escape(element.id);

	getXMLHttpRequest();

	if (xml_request) {
		xml_request.open("GET", url, true);
		xml_request.onreadystatechange = completeDel;
		xml_request.send(null);
	}
	// getXMLHtmlRequest(stateVal);
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: get all results 
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function getResultOperation(stateVal) {

	dataTable = document.getElementById("operation");
	dataTableBody = document.getElementById("operationData");

	skill = document.getElementById("skill").value;

	skillBranch = document.getElementById("skillBranch").value;

	questionNo = document.getElementById("questionNo").value;

	duration = document.getElementById("duration").value;

	skill_option = document.getElementById("skill").title;

	skillBranch_option = document.getElementById("skillBranch").title;

	var skillRequied = document.getElementById("skillRequied");
	skillRequied.innerHTML = '';
//	var skillBranchRequied = document.getElementById("skillBranchRequied");
//	skillBranchRequied.innerHTML = '';
//	var noQuRequied = document.getElementById("noQuRequied");
//	noQuRequied.innerHTML = '';

	if(skill =='' || skillBranch == ''||questionNo == ''){
		skillRequied.innerHTML = 'Please input all required fields!';
	}

	if (skill != '' && skillBranch != '' && questionNo != '') {
		count++;
		countTotal++;
		var url = "../maintainGrade/addMultipleSkills.do?method=" + stateVal
				+ "&skill=" + skill + "&skillBranch=" + skillBranch
				+ "&questionNo=" + questionNo + "&duration=" + duration
				+ "&id=" + count;
		getXMLHttpRequest();

		if (xml_request) {
			xml_request.open("POST", url, true);
			xml_request.onreadystatechange = completeAdd;
			xml_request.send(null);
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: get http request
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function getXMLHttpRequest() {

	if (window.XMLHttpRequest) {
		xml_request = new XMLHttpRequest();
	}
	// pour les navigateur: IE6,IE5.5,IE5
	else if (window.ActiveXObject) {
		xml_request = new ActiveXObject("Microsoft.XMLHTTP");
		if (!xml_request) {
			xml_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: add one row
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function completeAdd() {
	if (xml_request.readyState == 4) {
		if (xml_request.status == 200) {

			dataTableBody.appendChild(createRow(skill_option,
					skillBranch_option, questionNo, duration));
			gridColor();
			// getResult(stateVal);
			setGenerate();
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: delete one row
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function completeDel() {
	if (xml_request.readyState == 4) {
		if (xml_request.status == 200) {

			dataTableBody.removeChild(tr);
			countTotal--;
			gridColor();
			setGenerate();

			// getResult(stateVal);
		}
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: create one row operation
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function createRow(skill_option, skillBranch_option, questionNo, duration) {

	var row = document.createElement("tr");
	row.setAttribute("id", "tr" + count);

	var cell = document.createElement("td");
	var celldata = document.createTextNode(skill_option);
	cell.appendChild(celldata);
	row.appendChild(cell);

	var cell1 = document.createElement("td");
	var celldata1 = document.createTextNode(skillBranch_option);
	cell1.appendChild(celldata1);
	row.appendChild(cell1);

	var cell2 = document.createElement("td");
	var celldata2 = document.createTextNode(questionNo);
	cell2.appendChild(celldata2);
	row.appendChild(cell2);

	var cell3 = document.createElement("td");
	var celldata3 = document.createTextNode(duration);
	cell3.appendChild(celldata3);
	row.appendChild(cell3);

	var cell4 = document.createElement("td");
	var button = document.createElement("input");
	button.type = "button";
	button.value = "Delete";
	button.setAttribute("id", count);
	button.onclick = function() {
		deleteRow(this, "del")
	};
	// button.setAttribute('onclick','deleteRow(this,"Del");');

	cell4.appendChild(button);
	row.appendChild(cell4);

	return row;

}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: 
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function setGenerate() {
	var generate = document.getElementById("generate");
	if (countTotal > 0) {
		generate.disabled = false;
	} else {
		generate.disabled = true;
	}
}

/*******************************************************************************
 * @Created Date:03/02/2010
 * @Functionality: 
 * @Modified Date:
 * @Modified Person:
 ******************************************************************************/
function onlyNum(o) {
	o.value = o.value.replace(/[^\d]/g, '');
}
